package vip.liux.backend.application.serviceImpl.account;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import vip.liux.backend.application.service.account.AccountPhoneService;
import vip.liux.contracts.models.identity.IdentityUser;
import vip.liux.sms.ISmsSender;
import vip.liux.sms.NullSmsSender;

import static vip.liux.core.message.MessageUtils.getMessage;


@Service
public class AccountPhoneServiceImpl implements AccountPhoneService {
    protected final MessageSource messageSource;
    protected ISmsSender smsSender = new NullSmsSender();

    public AccountPhoneServiceImpl(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    /**
     * 发送确认码
     *
     * @param user              用户
     * @param confirmationToken 确认码
     */
    @Override
    public void sendConfirmationCode(IdentityUser user, String confirmationToken) {
        Assert.notNull(user.getPhoneNumber(), "phoneNumber must not be null");

        String name = user.getName() == null ? user.getUsername() : user.getName() + (user.getSurname() == null ? "" : " " + user.getSurname());

        smsSender.send(user.getPhoneNumber(), getMessage(messageSource, "account.phone.confirmation.sms", new Object[]{name, confirmationToken}));
    }

    /**
     * 发送安全码
     *
     * @param phoneNumber 手机号
     * @param code        安全码
     */
    @Override
    public void sendSecurityCode(String phoneNumber, String code) {
        smsSender.send(phoneNumber, getMessage(messageSource, "account.email.security-password.body", new Object[]{code}));
    }

    @Autowired(required = false)
    public void setSmsSender(ISmsSender smsSender) {
        this.smsSender = smsSender;
    }
}
